package org.zwy.gradetrack.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.zwy.gradetrack.common.Result;
import org.zwy.gradetrack.entity.Role;
import org.zwy.gradetrack.entity.User;
import org.zwy.gradetrack.service.RoleService;
import org.zwy.gradetrack.service.UserService;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RoleService roleService;

    /**
     * 分页查询用户列表
     */
    @GetMapping
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER')")
    public Result<IPage<User>> page(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String query,
            @RequestParam(required = false) Long roleId) {
        return Result.success(userService.pageUsers(page, size, query, roleId));
    }

    /**
     * 新增用户
     */
    @PostMapping
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    @Transactional
    public Result<Boolean> add(@RequestBody User user) {
        // 设置用户基本信息
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setStatus("1"); // 设置默认状态为启用
        
        // 保存用户
        boolean saved = userService.save(user);
        if (!saved) {
            return Result.error(500, "创建用户失败");
        }

        // 根据用户类型分配角色
        String roleCode;
        switch (user.getUserType()) {
            case "A":
                roleCode = "SYSTEM_ADMIN";
                break;
            case "T":
                roleCode = "TEACHER";
                break;
            case "S":
                roleCode = "GRADUATE";
                break;
            default:
                return Result.error(400, "无效的用户类型");
        }

        // 获取角色ID
        Role role = roleService.lambdaQuery()
                .eq(Role::getRoleCode, roleCode)
                .one();
        if (role == null) {
            return Result.error(404, "角色不存在");
        }

        // 分配角色
        List<Long> roleIds = Collections.singletonList(role.getId());
        boolean assigned = userService.assignRoles(user.getId(), roleIds);
        if (!assigned) {
            throw new RuntimeException("分配角色失败");
        }

        return Result.success(true);
    }

    /**
     * 编辑用户
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<Boolean> edit(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        user.setUpdateTime(LocalDateTime.now());
        return Result.success(userService.updateById(user));
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<Boolean> delete(@PathVariable Long id) {
        return Result.success(userService.removeById(id));
    }

    /**
     * 为用户分配角色
     */
    @PutMapping("/{userId}/roles")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<Boolean> assignRoles(
            @PathVariable Long userId,
            @RequestBody List<Long> roleIds) {
        return Result.success(userService.assignRoles(userId, roleIds));
    }
} 